package com.hundsun.cprs.yyt.web.action.trade;

import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.TradeCancelFlowQuery;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntrustCancelStatus;
import com.hundsun.cprs.yyt.service.trade.service.TradeCancelFlowService;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/trade/entrust/cancel")
public class TradeEntrustCancelAction extends BaseAction {
    
    @Autowired
    private TradeCancelFlowService cancelFlowService;
    @Autowired
    private TradeEntrustService tradeEntrustService;

    @RequestMapping("/list")
    public void list(@ModelAttribute("query") TradeCancelFlowQuery query, ModelMap model){
        if (query.getStartTime() == null){
            query.setStartTime(DateUtil.getBeginOfDay(new Date()));
        }
        if (query.getEndTime() == null){
            query.setEndTime(DateUtil.getEndOfDay(new Date()));
        }
        cancelFlowService.selectByPage(query);
        model.put("entrustCancelStatusMap", EnumEntrustCancelStatus.toMap());
    }

    @RequestMapping("/apply")
    public String applyRollback(Long entrustId, ModelMap model){
        TradeEntrust entrust = tradeEntrustService.getTradeEntrustById(entrustId);
        if (entrust == null) {
            return error(model, "委托单不存在");
        }
        try {

            tradeEntrustService.cancelEntrust(entrust.getEntrustNo());

        } catch (Exception e) {
            log.error("撤单失败:",e);
            return error(model,e.getMessage());
        }

        return "redirect:/trade/entrust/cancel/list.htm?entrustNo=" + entrust.getEntrustNo();
    }

    @Override
    protected void initBinder(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
